package com.tiza.xiaoyoubao.ui.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.squareup.picasso.Picasso;
import com.tianze.library.base.BaseFragment;
import com.tianze.library.view.SimpleDialog;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.AppContext;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.EditInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;

import org.simple.eventbus.Subscriber;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by mapple on 17/2/17.
 * 个人中心
 */

public class OneselfCenterFragment extends BaseFragment {

    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.sv_sllview)
    ScrollView sv_sllview;
    @BindView(R.id.view_userName)
    View view_userName;
    @BindView(R.id.view_userRules)
    View view_userRules;
    @BindView(R.id.view_binding)
    View view_binding;
    @BindView(R.id.view_setting)
    View view_setting;
    @BindView(R.id.view_wanchenglv)
    View view_wanchenglv;
    @BindView(R.id.view_service)
    View view_service;
    @BindView(R.id.view_version)
    View view_version;

    @BindView(R.id.tv_userTitle)
    TextView tv_userTitle;
    @BindView(R.id.tv_userId)
    TextView tv_userId;
    @BindView(R.id.tv_level)
    TextView tv_level;

    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);
    /* 请求识别码 */
    private static int CAMERA_REQUEST_CODE = 1;
    private static int GALLERY_REQUEST_CODE = 2;
    private static int CROP_REQUEST_CODE = 3;
    private File img;
    private int i = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_oneself_center_layout;
    }


    @Override
    protected void initData() {
    }

    @Subscriber(tag = Constants.TAG_SET_USER_PHONE_SUCCESS)
    private void onEdit(EditInfo info) {
        int type = info.getType();
        switch (type) {
            case EditInfo.TYPE_USER_PHONE:
                tv_userTitle.setText(info.getValue());
                break;

        }
    }

    @Override
    protected void initView() {
        setToolbarTitle("个人中心");
        if (TextUtils.isEmpty(userInfo.getWebzzCmsBuyerInfo().getNickname())) {
            tv_userTitle.setText(userInfo.getWebzzCmsBuyerInfo().getTelphone());
        } else {
            tv_userTitle.setText(userInfo.getWebzzCmsBuyerInfo().getNickname());
        }

        if (TextUtils.isEmpty(userInfo.getWebzzCmsBuyerInfo().getUserid())) {
            tv_userId.setText("未有");
        } else {
            tv_userId.setText("ID:" + userInfo.getWebzzCmsBuyerInfo().getUserid());
        }

        if (TextUtils.isEmpty(String.valueOf(userInfo.getWebzzCmsBuyerInfo().getLevel()))) {
            tv_level.setText("未评级");
        } else {
            tv_level.setText("等级L" + userInfo.getWebzzCmsBuyerInfo().getLevel());
        }
        if (!TextUtils.isEmpty(userInfo.getWebzzCmsBuyerInfo().getAvatar())) {
            Picasso.with(getActivity()).load(userInfo.getWebzzCmsBuyerInfo().getAvatar())
                    .placeholder(R.mipmap.club_head_default).error(R.mipmap.club_head_default)
                    .into(iv_head);
        }

    }

    @OnClick({
            R.id.iv_head,
            R.id.view_userName,
            R.id.view_userRules,
            R.id.view_binding,
            R.id.view_setting,
            R.id.view_wanchenglv,
            R.id.view_service,
            R.id.view_version,
            R.id.view_quit,
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                showCustomConfirmDialog("请选择上传方式", "手机相册", "手机拍照",
                        new SimpleDialog.OnSimpleClickListener() {
                            @Override
                            public void onClick(SimpleDialog simpleDialog) {
                                Intent intent = new Intent(
                                        Intent.ACTION_GET_CONTENT);
                                intent.setType("image/*");
                                getActivity().startActivityForResult(intent,
                                        GALLERY_REQUEST_CODE
                                );
                                simpleDialog.dismiss();
                            }
                        }, new SimpleDialog.OnSimpleClickListener() {
                            @Override
                            public void onClick(SimpleDialog simpleDialog) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                getActivity().startActivityForResult(intent, CAMERA_REQUEST_CODE);
                                simpleDialog.dismiss();
                            }
                        }
                );
                break;
            case R.id.view_userName:
                UIHelper.showUserName(mActivity);
                break;
            case R.id.view_userRules:
                UIHelper.showRank(mActivity);
                //UIHelper.showRules(mActivity);
                break;
            case R.id.view_binding:
                UIHelper.showAccountBinding(mActivity);
                break;
            case R.id.view_setting:
                UIHelper.showSetUp(mActivity);
                break;
            case R.id.view_wanchenglv:
                UIHelper.showAccountWanChengLv(mActivity);
                break;
            case R.id.view_service:
                UIHelper.showSerives(mActivity);
                break;
            case R.id.view_version:
                UIHelper.showVersion(mActivity);
                break;
            case R.id.view_quit:
                showConfirmDialog("确定退出?", new SimpleDialog.OnSimpleClickListener() {
                    @Override
                    public void onClick(SimpleDialog simpleDialog) {
                        AppContext.getInstance().setLogin(false);
                        Hawk.remove(Constants.KEY_USER_PASSWD);
                        UIHelper.showLogin(mActivity);
                        getActivity().finish();
                        simpleDialog.dismiss();
                    }
                });

                break;
            default:
                break;
        }

    }

    private Uri saveBitmap(Bitmap bm) {
        File tmpDir = new File(mActivity.getExternalCacheDir() + "/com.tiza.xiaoyoubao");

        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        img = new File(tmpDir.getAbsolutePath() + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Uri convertUri(Uri uri) {
        InputStream is = null;
        try {
            is = mActivity.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        getActivity().startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE) {

            if (data == null) {
                return;
            } else {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bm = extras.getParcelable("data");
                    Uri uri = saveBitmap(bm);
                    startImageZoom(uri);
                }
            }
        } else if (requestCode == GALLERY_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Uri uri;
            uri = data.getData();
            Uri fileUri = convertUri(uri);
            startImageZoom(fileUri);
        } else {
            if (requestCode == CROP_REQUEST_CODE) {
                if (data == null) {
                    return;
                }
                Bundle extras = data.getExtras();
                if (extras == null) {
                    return;
                }
                Bitmap bm = extras.getParcelable("data");
                Log.i("设置", "成功");
                //iv_head.setImageBitmap(bm);
                postHead(bm);
            }
        }
    }

    private void postHead(final Bitmap bitmap) {
        ApiHttpClient.setAvatar(this, userInfo.getWebzzCmsBuyerInfo().getTelphone(), img,
                new JsonCallback<UserInfo>(UserInfo.class) {
                    @Override
                    public void onError(Call call, Exception e) {
                        Picasso.with(getActivity())
                                .load(userInfo.getWebzzCmsBuyerInfo().getAvatar())//
                                .placeholder(R.mipmap.club_head_default)//
                                .error(R.mipmap.club_head_default)//
                                .into(iv_head);
                        toast("网络异常，请检查后再试");
                    }

                    @Override
                    public void onResponse(ResponseInfo<UserInfo> response) {
                        int code = response.getCode();
                        if (code == 1) {
                            showWarnDialog(response.getMessage());
                            return;
                        }
                        iv_head.setImageBitmap(bitmap);
                        toast("头像上传成功");
                    }
                }
        );
    }

    // 图片base64编码
    private String getImageString(Bitmap bitmap) {
        Bitmap bp = bitmap;
        bp = compressImage(bp);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bp.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        byte[] b = stream.toByteArray();
        StringBuilder sb = new StringBuilder();
        String stmp = "";
        for (int i = 0, len = b.length; i < len; i++) {
            stmp = Integer.toHexString(b[i] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            if (i != len - 1) {
                sb.append(",");
            }
        }
        return sb.toString().toUpperCase().trim();
    }

    // 质量压缩方法
    private Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 35) { // 循环判断如果压缩后图片是否大于35kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options,
                    baos
            );// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(
                baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }


}
